package org.robot.scm.pojos.platform;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.pojos.BaseNotify;
import org.robot.scm.pojos.TargetNotify;
import org.robot.scm.pojos.config.BaseConfig;
import org.robot.scm.pojos.enums.ChannelEnum;
import org.robot.scm.pojos.enums.HttpMethodEnum;
import org.robot.scm.utils.ShortLinkUtil;

@Data
@Builder
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class IBoxBaseNotify extends BaseNotify {

    private NoticeCategory category;
    private String createdAt;
    private Integer id;
    private String itemUrl;
    private String title;


    @Override
    public TargetNotify barkToNotifyBean(String deviceSn, BaseConfig config) {
        return TargetNotify.builder()
                .channelEnum(ChannelEnum.BARK)
                .notifyUrl(config.get().getNotifyChannel().getBark())
                .deviceSn(deviceSn)
                .topic(config.getCurrentPlatform().getNoticeTitle())
                .content(title)
                .detailUrl(getNoticeUrl())
                .icon(config.getCurrentPlatform().getIconUrl())
                .build();
    }

    @SneakyThrows
    @Override
    public TargetNotify robotToNotifyBean(String robotId, BaseConfig config) {
        String noticeUrl = URLEncoder.encode(getNoticeUrl(), StandardCharsets.UTF_8);
        noticeUrl = ShortLinkUtil.link(noticeUrl, "suo.im", 72);
        String content = config.robotText(robotId, URLEncoder.encode(title.concat("\n").concat(noticeUrl).concat("\n@所有人"), StandardCharsets.UTF_8));
        return TargetNotify.builder()
                .httpMethodEnum(HttpMethodEnum.POST)
                .channelEnum(ChannelEnum.ROBOT)
                .notifyUrl(config.robotUrl())
                .deviceSn(StringUtils.EMPTY)
                .topic(config.get().getNotifyChannel().getRobot().getBodyText())
                .content(content)
                .detailUrl(getNoticeUrl())
                .icon(config.getCurrentPlatform().getIconUrl())
                .build();
    }

    @Override
    public boolean equal(BaseNotify another) {
        return Objects.equals(id, ((IBoxBaseNotify) another).getId());
    }

    public String getNoticeUrl() {
        return "https://announcement.ibox.art/#/detail?noticeId=" + id;
    }


    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    static class NoticeCategory {

        private Integer id;
        private String name;
        private Integer sequence;
        private String updatedAt;
    }
}
